// 导入对应的模块
const fs = require('fs')
const path = require('path')

// 正则表达式
const regStyle = /<style>[\s\S]*<\/style>/
const regScript =/<script>[\s\S]*<\/script>/

// 读取文件
fs.readFile(path.join(__dirname+'/素材/index.html'),'utf-8',(err,data) => {
  if (err) {
    return console.log('读取文件失败',err.message)
  }
  // console.log('读取文件成功',data)
  resolveCss(data)
  resolveJS(data)
  resolveHTML(data)
})

function resolveCss(htmlStr) {
  const reg1 = regStyle.exec(htmlStr)
  // console.log(reg1[0],'reg1');
  const newCSS = reg1[0].replace('<style>','').replace('</style>','')
  // console.log(newCSS,'newCSS');
  fs.writeFile(path.join(__dirname,'/素材/index.css'),newCSS,(err) =>{
    if(err) {
      return console.log('写入文件失败',err.message);
    }
    console.log('写入文件成功');
  })
}

function resolveJS(htmlStr) {
  const reg2 = regScript.exec(htmlStr)
  const newJS = reg2[0].replace('<script>','').replace('</script>','')
  fs.writeFile(path.join(__dirname,'/素材/index.js'),newJS,(err) =>{
    if(err) {
      return console.log('写入文件失败',err.message);
    }
    console.log('写入文件成功');
  })
}

function resolveHTML(htmlStr) {
  const newHTML = htmlStr.replace(regStyle,'<link rel="stylesheet" href="./index.css">').replace(regScript,'<script src="./index.js"></script>')

  fs.writeFile(path.join(__dirname,'/素材/index2.html'),newHTML,err => {
    if(err) return console.log('写入html文件失败',err.message)
    console.log('写入html文件成功');
  })
}